import {
  Component,
  ViewEncapsulation,
  Input,
  OnInit,
  ChangeDetectorRef,
  HostBinding,
} from '@angular/core';

import { OverlayEntry, POSITION_MAP, FadeAnimation, composePositionSet, Direction } from '../shared/shared';

@Component({
  selector: 'fui-popover',
  templateUrl: './popover.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [
    FadeAnimation,
  ],
})
export class PopoverComponent extends OverlayEntry implements OnInit {
  @HostBinding('class.fui-popover-container') hostClass = true;

  /** Popover placement. */
  @Input() placement: Direction = 'top';

  /** Trigger method, support 'hover' and 'click'. */
  @Input() trigger: 'hover' | 'click' = 'hover';

  /** Append custom class on popover body for further customization. */
  @Input() customClass: string;

  classMap = {};

  get hasBackdrop() {
    return this.trigger === 'click';
  }

  constructor(private changeDetectionRef: ChangeDetectorRef) {
    super();
  }

  ngOnInit() {
    this.positions = composePositionSet(this.placement);
    this.setPosition(this.placement);
  }

  setPosition(placement: string) {
    this.setClassMap(placement);

    // 基于某些原因重渲染失败，需要手动触发。在其他项目Angular6.0 + CDK6.0无此问题.
    // TODO: 升级6.0之后移除
    this.changeDetectionRef.detectChanges();
  }

  setClassMap(placement: string) {
    this.classMap = {
      ['fui-popover']: true,
      [`fui-popover-placement-${placement}`]: true,
    };

    if (this.customClass) {
      this.classMap[this.customClass] = true;
    }
  }
}
